package com.duojuhe.i18n;
import com.duojuhe.common.config.DuoJuHeConfig;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.i18n.handler.I18nHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Aspect
@Component
@Configuration
public class LanguageAspect {
    @Resource
    private DuoJuHeConfig duoJuHeConfig;
    @Resource
    private I18nHandler i18nHandler;

    @Pointcut("execution(public com.duojuhe.common.result.ServiceResult com.duojuhe..*.*(..))")
    public void annotationLangCut() {

    }

    /**
     * 拦截controller层返回的结果，修改message字段
     *
     * @param joinPoint
     * @param returnResult
     */
    @AfterReturning(pointcut = "annotationLangCut()", returning = "returnResult")
    public void around(JoinPoint joinPoint, Object returnResult) {
        try {
            //未开启多语言切换
            if (!duoJuHeConfig.isLanguage()){
                return;
            }
            //从获取RequestAttributes中获取HttpServletRequest的信息
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            if (servletRequestAttributes==null){
                return;
            }
            HttpServletRequest request = servletRequestAttributes.getRequest();

            String langFlag = I18nUtils.getLangByRequest(request);
            if (StringUtils.isNotBlank(langFlag) && returnResult instanceof ServiceResult) {
                String lang = langFlag.toUpperCase();
                ServiceResult result = (ServiceResult) returnResult;
                String msg = result.getMessage();
                if (StringUtils.isNotBlank(msg)) {
                    msg = msg.trim();
                    if ("EN".equals(lang)) {
                        Locale locale = Locale.US;
                        msg = i18nHandler.getKey(msg, locale);
                    }
                }
                result.setMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
